<template>
    <BasicInformation :title="title" @action="handleAction" :primary-actions="mainActions"></BasicInformation>
    <div class="add">
       <div class="common-layout">
         <el-container>
           <el-main>
             <el-row>
               <el-col :span="24">
                 <div class="grid-content ep-bg-purple">
                   <h4>基本信息</h4>
                   <el-form :inline="true" :model="cwOtherIncome" :rules="rules" status-icon ref="formRef">
                     <el-form-item label="单据编号" prop="docCode">
                 <el-input 
                     v-model="cwOtherIncome.docCode"
                     style="width: 240px"
                     placeholder="请输入单据编号"
                     clearable
                     :disabled="true"
                     />
                         </el-form-item>
                     <!-- 客户 -->
                     <el-form-item label="客户" prop="cid">
                             <el-select
                               v-model="cwOtherIncome.cid" 
                               placeholder="请选择客户"
                               style="width: 240px"
                               clearable
                               filterable
                             >
                               <el-option
                                 v-for="customer in customerList"
                                 :key="customer.id"
                                 :label="`${customer.code} - ${customer.name}`"
                                 :value="customer.id"
                               />
                             </el-select>
                           </el-form-item>
 
                     <!-- 报价日期 -->
                     <el-form-item label="单据日期" prop="docDate">
                       <el-date-picker
                         v-model="cwOtherIncome.docDate"
                         type="date"
                         placeholder="请选择日期"
                         value-format="YYYY-MM-DD"
                         :disabled-date="disabledDate"
                       />
                     </el-form-item>
                     <!-- 业务员 -->
                      <el-form-item label="业务员" prop="uid">
                                            <el-select v-model="cwOtherIncome.uid" placeholder="请选择业务员" clearable filterable @change="" style="width: 240px;">
                                            <el-option v-for="item in userList"
                                            :key="item.id"
                                            :label="item.name"
                                            :value="item.id">
                                            </el-option>
                                            </el-select>                                                                     
                                        </el-form-item>
 
                     <!-- 部门 -->
                        <el-form-item label="部门" prop="did">
                                            <el-select
                                                v-model="cwOtherIncome.did"
                                                placeholder="请选择部门"
                                                style="width: 240px;"
                                                clearable
                                            >
                                                <el-option
                                                    v-for="dept in deptList"
                                                    :key="dept.id"
                                                    :label="dept.name"
                                                    :value="dept.id"
                                                />
                                            </el-select>
                                     </el-form-item>

                                         <el-form-item label="单据备注" prop="notes">
                                                <el-input 
                                                v-model="cwOtherIncome.notes"
                                                style="width: 240px"
                                                placeholder="请输入单据备注"
                                                clearable
                                                />
                                        </el-form-item>


                   </el-form>
                 </div>
               </el-col>
             </el-row>
           </el-main>
         </el-container>
       </div>
     </div>
   <!-- 收款信息表格 -->
  <div class="collection-info">
   
    <h4>收款信息</h4>
     <div class="toolbar">
    <el-button type="primary">商品信息</el-button>
    <el-button @click="addRow"  >继续添加</el-button>
    <el-button type="danger" @click="deleteRows" :disabled="selectedRows.length === 0">删除选中行</el-button>
    </div>
    <el-table :data="paymentAccounts" border style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" ></el-table-column>
      <el-table-column label="收款名称" align="center" width="150">
        <template #default="scope">
          <el-select 
            v-model="scope.row.payeeName" 
            placeholder="请选择收入名称"
            clearable
          >
            <el-option
              v-for="account in payeeNameList"
              :key="account.id"
              :label="account.name"
              :value="account.id"
            />
          </el-select>
        </template>
      </el-table-column>


      <el-table-column label="收款账户" align="center" width="150">
        <template #default="scope">
          <el-select 
            v-model="scope.row.accountName" 
            placeholder="请选择账户"
            clearable
          >
            <el-option
              v-for="account in payAccountList"
              :key="account.id"
              :label="account.account"
              :value="account.id"
            />
          </el-select>
        </template>
      </el-table-column>
      
      <el-table-column label="收款方式" align="center" width="150">
        <template #default="scope">
          <el-select 
            v-model="scope.row.payId" 
            placeholder="请选择方式"
            clearable
          >
            <el-option
              v-for="method in payIdList"
              :key="method.id"
              :label="method.payName"
              :value="method.id"
            />
          </el-select>
        </template>
      </el-table-column>

      <el-table-column label="收款金额" align="center" width="180">
        <template #default="scope">
          <el-input-number 
            v-model="scope.row.amount" 
            :min="0" 
            :precision="2"
            controls-position="right"
            style="width: 160px"
          />
        </template>
      </el-table-column>

        <el-table-column label="税率" align="center" width="100">
        <template #default="scope">
          <el-input 
            v-model="scope.row.tax" 
             @blur="validateTaxInput(scope.row)"
            :min="0" 
            :precision="2"
            controls-position="right"
            style="width: 60px"
          />
        </template>
      </el-table-column>

        <el-table-column label="税额" align="center" width="100">
        <template #default="scope">
          <el-input
            v-model="scope.row.taxAmount" 
            :readonly="true"
            :min="0" 
            :precision="2"
            controls-position="right"
            style="width: 60px"
          />
        </template>
      </el-table-column>

      <el-table-column label="手续费" align="center" width="150">
        <template #default="scope">
          <el-input-number 
            v-model="scope.row.fee" 
            :min="0" 
            :precision="2"
            controls-position="right"
            style="width: 120px"
          />
        </template>
      </el-table-column>

      <el-table-column label="交易号/票据号" align="center">
        <template #default="scope">
          <el-input 
            v-model="scope.row.transactionNo" 
            placeholder="请输入交易号"
            clearable
          />
        </template>
      </el-table-column>


      <el-table-column label="收款备注" align="center">
        <template #default="scope">
          <el-input 
            v-model="scope.row.notes" 
            placeholder="请输入备注"
            clearable
          />
        </template>
      </el-table-column>
      
    </el-table>
    <div class="validation-info">
   
    
  </div>




    <div class="total-summary">
      <div class="total-label">收款合计</div>
      <div class="total-amount">{{ formatPaymentTotal }}</div>
    </div>
  </div>

 
 
 
 
 </template>
 
 
 <script setup lang="ts">
 import { ref, reactive,withKeys ,watch,computed, onMounted} from 'vue';
 import BasicInformation from '@/public-view/BasicInformation.vue';
 import type {ComponentSize, FormInstance, FormRules} from 'element-plus'
 import {ElInput, ElAutoResizer, ElTableV2} from 'element-plus'
 import type {FunctionalComponent} from 'vue'
 import type {Column, InputInstance} from 'element-plus'
 import { useRouter,useRoute } from 'vue-router';
 import type { Customer } from '@/types/public-xs/Customer';
 import axios from 'axios';
 import { ElMessageBox, ElMessage } from 'element-plus'
 import type {CwOtherIncome,CwOtherIncomeDetail,CwOtherIncomeRefund,CwOtherIncomeRefundDetail,PaymentMethod,CwOtherIncomePayname}  from '@/types/public-xs/CwOtherIncome'
 import request from '@/util/request'
import type { User } from '@/types/rs/User';
import type { Department } from '@/types/rs/Department';
import type { PayAccount } from '@/types/cw/Public';
 
 let docCode=ref('')
 let sourceSheet=ref('')
 let title=ref('其他收款单')
 let pageNo=ref(1)
 let pageSize=ref(5)
 let allPage=ref(0)
 let router=useRouter()

//其他收入单对象
let cwOtherIncomeDetailList=ref<CwOtherIncomeDetail[]>([])
let cwOtherIncome=ref<CwOtherIncome>({
    id: 0,
    docCode: 'string',
    docDate: new Date,
    cid: null,
    uid: null,
    totalAmount:0,
    status: 0,
    notes: 'string',
    createBy: '毕建峰',
    createTime:new Date,
    updateBy: '毕建峰',
    updateTime:new Date,
    isDelete: 0,
    did:  null,
    didStr: 'string',
    uidStr: 'string',
    cidStr: 'string',
    details: cwOtherIncomeDetailList.value,
    refundAmount: 0,
    typeId:37
})



const rules = reactive<FormRules>({
  cid: [
    { required: true, message: '必须选择客户', trigger: ['blur', 'change'] },
    { type: 'number', message: '需要数值类型' }
  ],
  docDate: [
    { required: true, message: '必须选择单据日期', trigger: 'change' },
    { validator: (_, value, callback) => {
        if (new Date(value) > new Date()) 
          callback(new Error('不能选择未来日期'))
        callback()
      }
    }
  ],
  uid: [
    { required: true, message: '必须填写业务员', trigger: 'blur' },
    { pattern: /^\d+$/, message: '必须为数字ID' }
  ],
  did: [
    { required: true, message: '必须选择部门', trigger: 'change' }
  ]
})

// 收款信息校验规则
const tableRules = reactive({
  payeeName: [{ 
    required: true, 
    message: '必须选择收款名称', 
    trigger: ['blur', 'change'] 
  }],
  accountName: [{
    required: true,
    message: '必须选择收款账户',
    trigger: ['blur', 'change']
  }],
  amount: [
    { 
      required: true, 
      message: '必须填写金额', 
      trigger: ['blur', 'change'] 
    },
    { 
      validator: (_:any, value:number) => value > 0, 
      message: '金额必须大于0' 
    }
  ],
  tax: [
    { 
      validator: (_:any, value:number) => value >= 0 && value <= 100, 
      message: '税率需在0-100%之间' 
    }
  ],
  payId: [{
    required: true,
    message: '必须选择收款方式',
    trigger: ['blur', 'change']
  }]
})


// 表格行校验方法
const validateTableRows = () => {
  let isValid = true
  const errors: string[] = []
  
  paymentAccounts.value.forEach((row, index) => {
    const rowNumber = index + 1
    
    // 收款名称校验
    if (!row.payeeName) {
      errors.push(`第${rowNumber}行：必须选择收款名称`)
      isValid = false
    }
    
    // 金额校验
    if (row.amount <= 0) {
      errors.push(`第${rowNumber}行：金额必须大于0`)
      isValid = false
    }
    
    // 税率校验
    if (row.tax < 0 || row.tax > 100) {
      errors.push(`第${rowNumber}行：税率需在0-100%之间`)
      isValid = false
    }
  })

  if (!isValid) {
    ElMessage.error({
      message: `收款信息不完整：\n${errors.join('\n')}`,
      duration: 5000
    })
  }
  return isValid
}



 const disabledDate = (time: Date) => {
     return time.getTime() > Date.now()
 }
 // 修改handleAction方法
 const handleAction = (action:string) => {
   switch(action) {
     case 'choose':
       break
     case 'save-add':
          insertCwOtherIncome()
       break;
     case 'history':
       router.push('/home/cwOtherIncomeInfo')
       break;
   }
 }

 const mainActions = ref([
   { 
     name: 'save', 
     label: '保存', 
     type: 'primary',
     icon: 'DocumentAdd'
   },
   {
     name: 'save-add',
     label: '保存新增',
     disabled: false
   },
   {
     name: 'audit',
     label: '审核',
     hidden: false
   },
   {
     name: 'history',
     label: '历史单据',
     badge: 3 // 角标数字
   }
 ])

 
 
 //访问方法并获取单据编号
 let getDocCode=async()=>{
   let response=await request.post('/xs/counter/addCode',{docType:'QTSRD'})
   docCode.value=response.data.data
   cwOtherIncome.value.docCode=docCode.value
 }
 
 onMounted(async () => {
   await getDocCode()
   selectpayId()
   selectpayeeNameList()
 })

 let userList=ref<User[]>([])
let selectUser=async()=>{
  let response=await  request.post('/per/user/getAll')
  userList.value=response.data.data
  console.log(userList.value)
}
selectUser()

let deptList=ref<Department[]>([])
let selectDept=async()=>{
  let response=await  request.post('/per/dept/getAll')
  deptList.value=response.data.data
  console.log(deptList.value)
}
selectDept()


//获取到所有账户的方法
let payAccountList = ref<PayAccount[]>([])
let  selectAllBankAccount=async()=>{
  let accountRes = await request.post("basic/Account/selectAllAccount")
  payAccountList.value = accountRes.data.data
}
selectAllBankAccount()


 //获取到付款方式的方法
 let payIdList=ref<PaymentMethod[]>([])
 let selectpayId=async()=>{
  let response=await request.post("/cw/PaymentMethodController/selectPaymentMethod")
   payIdList.value=response.data.data
   console.log(payIdList.value)
 }

 //获取收款名字的方法
 let payeeNameList=ref<CwOtherIncomePayname[]>([])
 let selectpayeeNameList=async()=>{
   let response= await request.post("/cw/PaymentMethodController/selectCwOtherIncomePayname")
   payeeNameList.value=response.data.data
 }
 




 
 // todo
 const generateUUID = () => {
     return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
     const r = (Math.random() * 16) | 0
     const v = c === 'x' ? r : (r & 0x3) | 0x8
     return v.toString(16)
   })
 }
 //动态加载客户
let customerList = ref<Customer[]>([])
let selectCustomer = async () => {
    let response = await request.post('/basic/Customer/selectAllCustomer')
    customerList.value = response.data.data
    console.log(customerList.value)

}
selectCustomer()

 

 const newSelectedRows = ref<any[]>([])
 
 // 处理选中行变化
 const newHHandleSelectionChange = (selection: any[]) => {
   newSelectedRows.value = selection
 }
 
 
 
 //价格校验
 const validatePrice = (row:any) => {
   row.actualPrice = row.actualPrice.replace(/[^\d.]/g, '')
 }
 
 // 含税价计算
 const calculateTaxPrice = (row:any) => {
   if (row.actualPrice && row.vatRate) {
     row.taxIncludedPrice = (row.actualPrice * (1 + row.vatRate/100)).toFixed(2)
   }
 }
 

 //明细数据列表              
 const paymentAccounts = ref([
  {
    id: 1,
    accountName:1,
    payId: 0,
    amount: 0,
    fee: 0,
    payeeName:1,//收入名称
    tax:0,//税率
    taxAmount:0,//税额
    notes:'',//单据备注
  }
])

const bankAccounts = ref([
  { value: '招行', label: '招商银行（尾号8899）' },
  { value: '工行', label: '工商银行（尾号5566）' }
])


watch(
  () => paymentAccounts.value,
  (rows) => {
    rows.forEach(row => {
      if (row.tax != null && row.amount != null) {
        // 税率按百分比计算（如输入6表示6%）
        row.taxAmount = Number((row.amount * row.tax / 100).toFixed(2))
      }
    })
  },
  { deep: true } // 开启深度监听
)

const validateTaxInput = (row: any) => {
  // 转换为数字类型
  let taxValue = Number(row.tax);
  
  // 处理 NaN 情况
  if (isNaN(taxValue)) taxValue = 0;
  
  // 限制范围
  taxValue = Math.max(0, Math.min(100, taxValue));
  
  // 保留两位小数
  row.tax = Number(taxValue.toFixed(2));
}


// 计算属性
const formatPaymentTotal = computed(() => {
  const total = paymentAccounts.value.reduce(
    (sum, row) => sum + Number(row.amount || 0) - Number(row.fee || 0),
    0
  )
  cwOtherIncome.value.totalAmount = total
  return `¥${total.toFixed(2)}`
})


  // 在script setup部分新增代码
const selectedRows = ref<any[]>([]) // 存储选中行数据

// 添加行（带唯一标识）
const addRow = () => {
  paymentAccounts.value.push({
    id:Number(generateUUID()), // 使用已有的UUID生成方法
    accountName:1,
    payId: 1,
    amount: 0,
    fee: 0,
    payeeName: 1,
    tax: 0,
    taxAmount: 0,
    notes: ''
  })
}

// 处理选中行变化
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
}

// 删除选中行（带确认对话框）
const deleteRows = async () => {
  try {
    await ElMessageBox.confirm(
      `确定删除选中的${selectedRows.value.length}条记录吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 通过ID过滤保留未选中的行[6,7](@ref)
    const selectedIds = new Set(selectedRows.value.map(row => row.id))
    paymentAccounts.value = paymentAccounts.value.filter(row => !selectedIds.has(row.id))
    selectedRows.value = []
    
    ElMessage.success('删除成功')
  } catch (cancel) {
    // 用户取消操作不处理
  }
}

const generateDetails = () => {
  return paymentAccounts.value.map(item => ({
    id:0,
    payeeName: item.payeeName,
    payId: item.payId,
    amount: item.amount,
    fee: item.fee,
    tax: item.tax,
    taxAmount: item.taxAmount,
    notes: item.notes,
    createBy:'毕建峰',
    createTime:new Date,
    updateBy:'毕建峰',
    updateTime:new Date,
    mainCode:cwOtherIncome.value.docCode,
    accountId:item.accountName,
    isDelete:0
  })) as CwOtherIncomeDetail[]
}

const formRef = ref<FormInstance>()
  //新增其他收入单
const insertCwOtherIncome = async () => {
  try {
    // 基础表单校验
    const formEl = formRef.value
    if (!formEl) return
    await formEl.validate()

    // 表格数据校验
    if (paymentAccounts.value.length === 0) {
      ElMessage.warning('至少需要添加一条收款记录')
      return
    }
    
    if (!validateTableRows()) return

    // 服务端提交逻辑
    const details = generateDetails()
    const res = await request.post("/cw/CwOtherIncomeController/insertCwOtherIncome", {
      cwOtherIncome: cwOtherIncome.value,
      details: details
    })

    if (res.data.code == 200) {
      ElMessage.success('提交成功')
      router.push('/home/cwOtherIncomeInfo')
    }
  } catch (error) {
    console.error('表单验证失败', error)
    ElMessage.error('请检查红色标记的错误项')
  }
}




 
 </script>
 
 
 <style scoped>
 .el-row {
     margin-bottom: 20px;
 }
 
 .el-row:last-child {
     margin-bottom: 0;
 }
 
 .el-col {
     border-radius: 4px;
 }
 
 .grid-content {
     border-radius: 4px;
     min-height: 36px;
 }
 .required-label::after {
   content: "*";
   color: #f56c6c;
   margin-left: 4px;
 }
 
 .goods-table {
   margin-top: 20px;
 }
 
 .toolbar {
   margin-bottom: 15px;
   padding: 10px;
   background: #f5f7fa;
   border-radius: 4px;
 }
 
 .el-table :deep(.el-input__inner) {
   text-align: center;
 }
 .total-summary {
   background: #fff8dc; /* 浅黄色背景 */
   padding: 12px 20px;
   display: flex;
   justify-content: flex-end;
   border: 1px solid #ebeef5;
   border-top: none;
 }
 
 .total-label {
   font-weight: 600;
   color: #606266;
   margin-right: 30px;
 }
 
 .total-amount {
   color: #f56c6c;
   min-width: 120px;
   text-align: right;
   font-family: Arial, sans-serif;
 }
 .pagination-wrapper {
     margin-top: 16px;
     display: flex;
     justify-content: flex-end;
 }
 .dialog-header {
   display: flex;
   align-items: center;
   margin-bottom: 15px;
   flex-wrap: wrap;
   gap: 10px;
 }
 
 .date-label {
   color: #606266;
   margin: 0 10px;
 }
 
 .date-separator {
   margin: 0 8px;
   color: #c0c4cc;
 }
 
 .selected-info {
   margin: 12px 0;
   display: flex;
   align-items: center;
   gap: 10px;
   color: #606266;
 }
 
 .dialog-footer {
   display: flex;
   justify-content: space-between;
   align-items: center;
   margin-top: 15px;
 }
 
 .pagination-info {
   color: #606266;
 }
 
 .action-buttons {
   display: flex;
   gap: 15px;
 }
 
 :deep(.el-dialog__header) {
   border-bottom: 1px solid #ebeef5;
 }

 .collection-info {
  margin: 20px 0;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 4px;
}

.source-info {
  margin-top: 20px;
  border-top: 2px solid #ebeef5;
  padding-top: 15px;
}

.toolbar {
  margin-bottom: 15px;
}

.total-summary {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-top: 15px;
  padding: 10px;
  background: #f4f4f5;
  border-radius: 4px;
}

.total-label {
  font-weight: 600;
  margin-right: 20px;
}

.total-amount {
  font-size: 18px;
  color: #f56c6c;
  font-weight: bold;
}
.validation-info {
  margin: 15px 0;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 4px;
}

.amount-summary {
  margin-top: 10px;
  color: #606266;
  font-size: 14px;
}

.el-alert {
  margin-bottom: 10px;
}

.collection-info {
  .header-wrapper {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    
    h4 {
      margin: 0;
    }
    
    .action-buttons {
      display: flex;
      gap: 8px;
    }
  }
}
/* 错误状态样式 */
:deep(.el-form-item.is-error) {
  .el-input__inner, .el-select__wrapper {
    box-shadow: 0 0 3px rgba(245,108,108,.3);
  }
}

/* 表格错误提示 */
.el-table {
  .error-cell {
    .cell {
      position: relative;
      &::after {
        content: "!";
        position: absolute;
        right: 5px;
        color: #f56c6c;
        font-weight: bold;
      }
    }
  }
}


 </style>







